package com.edushare.controller;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.edushare.entity.Group;
import com.edushare.entity.GroupMedia;
import com.edushare.entity.Member;


public class GroupMediaController {

	// JSON parser class
	JSONParser jsonParser = new JSONParser();

	private JSONController jController = new JSONController();
	private static String retrieve_media_url = "http://unifiq.5kportal.com/debbieunifiq/retrieve_groupmedia.php";

	// url to update product
	private static final String url_update_icon = "http://unifiq.5kportal.com/debbieunifiq/update_group_media.php";

	private static final String TAG_SUCCESS = "success",
			TAG_GROUPID = "groupID", TAG_IMAGEPATH = "imagePath",
			TAG_MEDIAID = "mediaID";

	public ArrayList<GroupMedia> retrieveGroupsMedia(String groupID) {
		ArrayList<GroupMedia> groupsList = new ArrayList<GroupMedia>();
		JSONArray groupJArr = null;

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(TAG_GROUPID, String.valueOf(groupID)));
		JSONObject json = jController.makeHttpRequest(retrieve_media_url,
				"GET", params);

		try {
			int success = json.getInt(TAG_SUCCESS);

			if (success == 1) {
				groupJArr = json.getJSONArray("media");

				for (int i = 0; i < groupJArr.length(); i++) {
					JSONObject jObject = groupJArr.getJSONObject(i);

					int grpID = jObject.getInt(TAG_GROUPID);
					int mediaID = jObject.getInt(TAG_MEDIAID);
					String imagePath = jObject.getString(TAG_IMAGEPATH);

					GroupMedia gp = new GroupMedia();

					gp.setGroupID(grpID);
					gp.setImagePath(imagePath);
					gp.setMediaID(mediaID);

					groupsList.add(gp);

				}
			} else {
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return groupsList;
	}

	public void updateGroupIcon(int mediaID, String imagename) {

		String url = "http://unifiq.5kportal.com/images/post_images/"
				+ imagename;

		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(TAG_IMAGEPATH, url));
		params.add(new BasicNameValuePair(TAG_MEDIAID, String.valueOf(mediaID)));

		// sending modified data through http request
		// Notice that update product url accepts POST method
		JSONObject json = jsonParser.makeHttpRequest(url_update_icon, "POST",
				params);

		// check json success tag
		try {
			int success = json.getInt(TAG_SUCCESS);

			if (success == 1) {
				// successfully updated
			} else {
				// failed to update product
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}
